module Fetch (clock, reset, ex_if_stall, fw_if_id_stall,
    if_id_proximopc, if_id_instrucao,
    id_if_selfontepc, id_if_rega, id_if_pcimd2ext,
    id_if_pcindex, id_if_seltipopc,
    if_mc_en, if_mc_addr, mc_if_data);

    input               clock;
	input               reset;

	// Execute
	input               ex_if_stall;

	// Forwarding
	input               fw_if_id_stall;

	// Decode
	output	reg	[31:0]  if_id_proximopc;
	output	reg	[31:0]  if_id_instrucao;
	input		[0:0]	id_if_selfontepc;
	input       [31:0]  id_if_rega;
	input       [31:0]	id_if_pcimd2ext;
	input       [31:0]	id_if_pcindex;
	input       [1:0]	id_if_seltipopc;

	// Memory Controller
	output	[0:0]	if_mc_en;
	output	[31:0]	if_mc_addr;
	input	[31:0]	mc_if_data;

    reg [31:0] pc;
	reg  [0:0] reg_if_mc_en;
	assign if_mc_en = reg_if_mc_en;
	assign if_mc_addr = pc;
        
    // Reset fetch registers 
    always @(negedge(reset)) begin
        
        pc = 32'b0;
        if_id_proximopc = 32'b0;
        if_id_instrucao = 32'b0;
		reg_if_mc_en = 1'b0 ;

    end
    

	always @(negedge(clock)) begin

		reg_if_mc_en = 1'b1;

		if (!fw_if_id_stall) begin

			// Stall
			if (ex_if_stall) begin

				if_id_proximopc = pc;
				if_id_instrucao = 32'b0;

			end else begin

				// Fetches next instruction
				if_id_instrucao = mc_if_data;

                // Resolves PC value
				if (id_if_selfontepc) begin 

                    case (id_if_seltipopc)

                        2'b00: begin            
                            pc = id_if_pcimd2ext;
                        end

                        2'b01: begin
                            pc = id_if_rega; 
                        end

                        2'b10: begin
                            pc = id_if_pcindex;
                        end

                        2'b11: begin
                            pc = 32'b00000000000000000000000001000000;
                        end

                    endcase

				end else begin

                    pc = pc + 4;

				end
                
                if_id_proximopc = pc;

            end

		end

	end

endmodule
